<?php

namespace app\xcxapi\service;

use app\admin\service\AccountService;
use app\api\controller\Wxpay;
use app\api\service\QrcodeServer;
use app\api\service\WxpayService;
use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\AuditionModel;
use app\models\CourseLogModel;
use app\models\CourseModel;
use app\models\ContractModel;
use app\models\DictionaryModel;
use app\models\GradesContractModel;
use app\models\GoodsContractModel;
use app\models\CourseContractModel;
use app\models\FollowUpLogModel;
use app\models\GoodsModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\MarkingModel;
use app\models\ParentInformationModel;
use app\models\PushMessageModel;
use app\models\StudentModel;
use app\models\CampusModel;
use app\models\StudentSubjectClassModel;
use app\models\TimetableModel;
use app\models\UserModel;
use app\models\ReceivablesModel;
use app\xcxapi\validate\CustomerValidate;
use app\models\AllocationCampusModel;
use app\models\AllocationOnlyModel;
use think\Db;

class CustomerService extends BaseService
{
    /**
     * 验证
     *
     * @var CustomerValidate
     */
    protected $customerValidate;

    /**
     * 客户列表
     * User: wufeng
     * Date: 2019/5/15.
     *
     * @param $params
     *
     * @return array
     */
    public function customerLists($params)
    {
        try {
            $where = [];
            //按手机号、姓名、顾问搜索
            if (isset($params['word']) && '' !== $params['word']) {
                $where['phone|student_name|name|course_consultant'] = ['like', '%'.$params['word'].'%'];
            }
            //客户状态
            if (isset($params['follow_up']) && '' !== $params['follow_up']) {
                $where['follow_up'] = $params['follow_up'];
            }
            $order = 'id desc';
            $time = '';
            switch ($params['table_type']) {
                case 'my':
                    //我的客户
                    $where['user_id'] = xcxapi_get_current_user_id();

                    break;
                case 'public':
                    //公共客户
                    $where['user_id'] = 0;

                    break;
                case 'assigned':
                    //已分配客户
                    $where['course_consultant_type'] = 1;

                    break;
                case 'today':
                    //今天待跟进
                    $where['next_follow_up_record'] = date('Y-m-d');

                    break;
                case 'tomorrow':
                    // 明天待跟进
                    $where['next_follow_up_record'] = $date = date('Y-m-d', strtotime('+1 day'));

                    break;
                case 'week':
                    //本周待跟进
                    $time = 'week';

                    break;
                case 'all':
                    break;
            }
            $where['status'] = 1;
			$where['campus_id'] = ['in',xcxapi_get_current_campus_id()];
            if ($time) {
                $this->data = (new StudentModel())
                    ->where($where)
                    ->whereTime('next_follow_up_record', $time)
                    ->order($order)
                    ->select()
                    ->toArray()
                ;
            } else {
                $this->data = (new StudentModel())
                    ->where($where)
                    ->order($order)
                    ->select()
                    ->toArray()
                ;
            }

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
            foreach ($this->data as &$val) {
                $val['follow_up_text'] = DictionaryModel::getById($val['follow_up'], 'name');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 获取客户编辑信息
	 * User: wufeng
	 * Date: 2020/02/29
	 *
	 * @param $params
	 * @return array
	 */
	public function customer($params)
	{
		try {
			$this->data = (new StudentModel())
				->where(['id' => $params['id']])
				->find()
			;
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
	}
	
	 /**
     * 获取校区教务/学管师
	 * User: chenben
	 * Date: 2020/04/04
	 * @param $params
	 * @return array
     *
     */
    public function getByCampusEduUser($params)
	{
		try {
            $users = (new UserModel())
				->where(['campus_id' => ['in', xcxapi_get_current_campus_id()], 'group_type' => 5])
				->order('id desc')
				->field('id,name')
				->select()
				->toArray(); //获取教务人员
            if(xcxapi_get_current_wtype() != 5){
                $arr[] = [
                    'id' => xcxapi_get_current_user_id(),
                    'name' => xcxapi_get_current_name(),
                ];
                $users = array_merge($users, $arr);
            }
			$this->data = $users;
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;

    }

	/**
	 * 完成收款
	 * User: chenben
	 * Date: 2020/04/04
	 *
	 * @param $params
	 * @return array
	 */
	public function customerReceivables($params)
	{
		try {
            $contract = (new ContractModel())->get($params['contract_id']);
            $arr_json_all = $params['campus_achievement_list'];  //校区业绩分配
            $arr_json_only = $params['only_achievement_list'];  //个人业绩分配
			$arr_json_decode_all = $arr_json_all;  //校区业绩
            $arr_json_decode_only = $arr_json_only; //个人业绩
            $arr_json_all = [];
            if (count($arr_json_decode_all) > 0) {    //校区业绩
                for ($i = 0; $i < count($arr_json_decode_all); $i++) {
                    $item = $arr_json_decode_all[$i];
					if($item['campus_id'] != null && $item['department_id'] != null){
                    $cell_all = [];
                    $cell_all['contract_number'] = $contract['contract_number'];
                    $cell_all['campus_id_all'] = $item['campus_id'];
                    $cell_all['campus_id_all_text'] = $item['campus_name'];
                    $cell_all['assignment_all'] = $item['department_id'];
                    $cell_all['assignment_all_text'] = $item['department_name'];
                    $cell_all['rate_all'] = $item['rate'];
					$cell_all['receipt_number'] = $params['receipt_number'];
					$cell_all['operator'] = xcxapi_get_current_user_id();
                    $cell_all['rate_all_money'] = round(($params['amountcollected'] * ($item['rate'] / 100))) * 100;
                    $cell_all['amount_already_all'] = $params['amountcollected'] * 100;
                    $arr_json_all[] = $cell_all;
					}
                }
            }
            $arr_json_only = [];
            if (count($arr_json_decode_only) > 0) { //个人业绩
                for ($i = 0; $i < count($arr_json_decode_only); $i++) {
                    $item = $arr_json_decode_only[$i];
					if($item['only_id'] != null && $item['department_id'] != null){
                    $cell_only = [];
                    $cell_only['contract_number'] = $contract['contract_number'];
                    $cell_only['payee_only'] = $item['only_id'];
                    $cell_only['payee_only_text'] = $item['only_name'];
                    $cell_only['assignment_only'] = $item['department_id'];
                    $cell_only['assignment_only_text'] = $item['department_name'];
                    $cell_only['rate_only'] = $item['rate'];
                    $cell_only['campus_id'] = $contract['campus_id'];  //当前校区ID
					$cell_only['receipt_number'] = $params['receipt_number'];
					$cell_only['operator'] = xcxapi_get_current_user_id();
                    $cell_only['rate_only_money'] = round(($params['amountcollected'] * ($item['rate'] / 100))) * 100;
                    $cell_only['amount_already_only'] = $params['amountcollected'] * 100;
                    $arr_json_only[] = $cell_only;
					}
                }
            }
            if(count($arr_json_all) > 0 ){
                    if(!(new AllocationCampusModel())->saveAll($arr_json_all)){
                        $this->error('插入校区业绩信息失败', null, '', 1);
                    }
            }
            if(count($arr_json_only) > 0 ){
                if(!(new AllocationOnlyModel())->saveAll($arr_json_only)){
                    $this->error('插入个人业绩信息失败', null, '', 1);
                }
            }
			$receivables['contract_number'] = $contract['contract_number'];
			$receivables['paydate'] = date('Y-m-d');
			$receivables['payee'] = $params['payee_id'];
			$receivables['flow_number'] = 'LSH'.date('md').$params['contract_id'];
			$receivables['amount'] = $params['amountcollected'] * 100;
			$receivables['campus_id'] = $contract['campus_id'];
			$receivables['receipt_number'] = $params['receipt_number'];
			$receivables['payment_method'] = $params['pay_type_id'];
			$receivables['picture'] = $params['image_str'];
			//收款管理写入
			$res = (new ReceivablesModel())->save($receivables);
			
			 //现金支付
			if($receivables['payment_method'] == '79'){
				//更新订单状态及金额
				$data['amount'] = $params['amountcollected'] * 100;//已收款金额

				/*********************财务流程**********************/
				//应收【total_amount】  项目收费【amount】  实收【net_receipts】   欠费【stay_amount】    支出【expenditure】   余额【balance】    储值【Storedvalue】
				$total_amount_money = $contract['total_amount']; //应收
				$amount_money = $contract['amount'] +  $data['amount']; //项目收费
				$storedvalue = 0;
				$net_receipts = 0;
				$des_storedvalue = 0;
                $amount_allocation = 0;//分配金额
				if($amount_money <= $total_amount_money){
					$storedvalue = 0;   //储值
					$net_receipts = $amount_money;
                    $amount_allocation = $data['amount'];
				}else if($amount_money > $total_amount_money){
					$des_storedvalue = ($amount_money - $total_amount_money); //储蓄增量
					$storedvalue = ($amount_money - $total_amount_money) + $contract['storedvalue'];
					$amount_money = $total_amount_money;
                    $net_receipts = $amount_money;
                    $amount_allocation = ($total_amount_money -  $contract['amount']);
				}

				$stay_amount_money = ($total_amount_money - $amount_money);  //欠费
				$expenditure_money = $contract['expenditure']; //支出[课消]

				/********************END*****************************/
				{
                    if($amount_allocation > 0){
                        $checked_ids = $params['checked_ids'];//资金分配
                        $checked_ids_arr = explode(',',$checked_ids);

                        //规则：默认先把物品的钱付完
                        for($h = 0; $h < count($checked_ids_arr); $h ++){
                            $pos_value_arr = explode('-',$checked_ids_arr[$h]);
                            if($amount_allocation > 0) {
                                if ($pos_value_arr[1] == 3) {  //物品
                                    $res_good = (new GoodsContractModel())->get(['id' => $pos_value_arr[0]]);
                                    $des_good_amount = (($res_good['net_receipts'] - $res_good['assessed_amount']) - $res_good['payment']);
                                    if($amount_allocation >= $des_good_amount){
                                        $amount_allocation = $amount_allocation - $des_good_amount;
                                        $des_good_amount_ = $res_good['payment'] + $des_good_amount;
                                        $payment_balance = $res_good['payment_balance'] + $des_good_amount;
                                        (new GoodsContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_, 'payment_balance' => $payment_balance]);
                                    }else{
                                        $des_good_amount_ = $res_good['payment'] + $amount_allocation;
                                        $payment_balance = $res_good['payment_balance'] + $amount_allocation;
                                        (new GoodsContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_,'payment_balance' => $payment_balance]);
                                        $amount_allocation = 0;
                                    }
                                }
                            }
                        }
                        //分课程-分班级-求总应收金额
                        if($amount_allocation > 0) {
                            $net_receipts_amount_total = 0;
                            for ($h = 0; $h < count($checked_ids_arr); $h++) {
                                $pos_value_arr = explode('-', $checked_ids_arr[$h]);
                                if ($pos_value_arr[1] == 1) {  //课程
                                    $res_course = (new CourseContractModel())->get(['id' => $pos_value_arr[0]]);
                                    $net_receipts_amount_total = $net_receipts_amount_total + ($res_course['net_receipts'] - $res_course['assessed_amount']);
                                } else if ($pos_value_arr[1] == 2) {   //班级
                                    $res_grades = (new GradesContractModel())->get(['id' => $pos_value_arr[0]]);
                                    $net_receipts_amount_total = $net_receipts_amount_total + ($res_grades['net_receipts'] - $res_grades['assessed_amount']);
                                }

                            }


                            //分配

                            for ($h = 0; $h < count($checked_ids_arr); $h++) {
                                $pos_value_arr = explode('-', $checked_ids_arr[$h]);
                                    if ($pos_value_arr[1] == 1) {  //课程
                                        $res_course = (new CourseContractModel())->get(['id' => $pos_value_arr[0]]);
                                        $rate_amount = round(($res_course['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
                                        //抵充欠费
                                        $rate_amount_total = $rate_amount;
                                        $contract_number = ContractModel::get(['id' => $res_course['contract_id']])['contract_number'];
                                        $res_info = (new StudentSubjectInfosClassModel())->where(['status' => 1, 'report_status' => 1, 'arrears_status' => 1, 'give_status' => 1, 'contract_number' => $contract_number, 'course_id' => $res_course['course_id']])->select();
                                        foreach ($res_info as $value){
                                            $info_id = $value['id'];
                                            if($rate_amount_total > 0) {
                                                if (($rate_amount_total + $value['arrears_amount']) >= 0) {
                                                    if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_status' => 0, 'arrears_amount' => 0])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    $rate_amount_total = ($rate_amount_total + $value['arrears_amount']);
                                                } else {
                                                    $value['arrears_amount'] = ($rate_amount_total + $value['arrears_amount']);
                                                    if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_amount' => $value['arrears_amount']])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    break;
                                                }
                                            }
                                        }


                                        $rate_amount_ = $res_course['payment'] + $rate_amount;
                                        $payment_balance = $res_course['payment_balance'] + $rate_amount;
                                        (new CourseContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]);  //更新付款金额


                                        //更新合同应收分配课时
                                        $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
                                        $nums = round(($rate_amount / $price_),2);

                                        $course_paid_nums_arr = explode(',',$contract['course_paid_nums']);
                                        $course = explode(',',$contract['course']);
                                        for($l = 0; $l < count($course); $l ++){
                                            if($course[$l] == $res_course['course_id']){
                                                $course_paid_nums_arr[$l] = $course_paid_nums_arr[$l] + $nums;
												$C_Number = $contract['contract_number'];  //合同号
												$Course_Id = $res_course['course_id']; //课程ID
												$Report_Status = 1; //课程
												if((new StudentSubjectInfosClassModel())->get(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])){
													
													(new StudentSubjectInfosClassModel())->where(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])->update(['surplus_class_elimination' => $course_paid_nums_arr[$l]]);
												}
                                            }
                                        }
                                        $contract['course_paid_nums'] = implode(',',$course_paid_nums_arr);


                                    } else if ($pos_value_arr[1] == 2) {   //班级
                                        $res_grades = (new GradesContractModel())->get(['id' => $pos_value_arr[0]]);
                                        $rate_amount = round(($res_grades['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
                                        //抵充欠费
                                        $rate_amount_total = $rate_amount;
                                        $contract_number = ContractModel::get(['id' => $res_grades['contract_id']])['contract_number'];
                                        $res_info = (new StudentSubjectInfosClassModel())->where(['status' => 1, 'report_status' => 2, 'arrears_status' => 1, 'give_status' => 1, 'contract_number' => $contract_number, 'course_id' => $res_grades['course_id']])->select();
                                        foreach ($res_info as $value){
                                            $info_id = $value['id'];
                                            if($rate_amount_total > 0) {
                                                if (($rate_amount_total + $value['arrears_amount']) >= 0) {
                                                    if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_status' => 0, 'arrears_amount' => 0])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    $rate_amount_total = ($rate_amount_total + $value['arrears_amount']);
                                                } else {
                                                    $value['arrears_amount'] = ($rate_amount_total + $value['arrears_amount']);
                                                    if (!(new StudentSubjectInfosClassModel())->where(['id' => $info_id])->update(['arrears_amount' => $value['arrears_amount']])) {
                                                        $this->error('更新课消欠费金额失败', null, '', 1);
                                                    }
                                                    break;
                                                }
                                            }
                                        }

                                        $rate_amount_ = $res_grades['payment'] + $rate_amount;
                                        $payment_balance = $res_grades['payment_balance'] + $rate_amount;
                                        (new GradesContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]); //更新付款金额

                                        //更新合同应收分配课时
                                        $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
                                        $nums = round(($rate_amount / $price_),2);

                                        $grades_course_paid_nums_arr = explode(',',$contract['grades_course_paid_nums']);
                                        $grades_course = explode(',',$contract['grades_course']);
                                        for($l = 0; $l < count($grades_course); $l ++){
                                            if($grades_course[$l] == $res_grades['course_id']){
                                                $grades_course_paid_nums_arr[$l] = $grades_course_paid_nums_arr[$l] + $nums;
												$C_Number = $contract['contract_number'];  //合同号
												$Course_Id = $res_grades['course_id']; //课程ID
												$Report_Status = 2; //班级
												if((new StudentSubjectInfosClassModel())->get(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])){
													
													(new StudentSubjectInfosClassModel())->where(['report_status' => $Report_Status, 'course_id' => $Course_Id, 'contract_number' => $C_Number])->update(['surplus_class_elimination' => $grades_course_paid_nums_arr[$l]]);
												}
													
                                            }
                                        }

                                        $contract['grades_course_paid_nums'] = implode(',',$grades_course_paid_nums_arr);
                                    }

                            }
                        }


                    }

				}
                //学费余额
                $payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $params['contract_id']])->sum('payment_balance');
                $payment_course_balance = (new CourseContractModel())->where(['contract_id' => $params['contract_id']])->sum('payment_balance');
                $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和

                $contract_data['course_paid_nums'] = $contract['course_paid_nums'];
                $contract_data['grades_course_paid_nums'] = $contract['grades_course_paid_nums'];
				$contract_data['course_elimination'] = $contract['course_paid_nums'];
                $contract_data['grades_course_elimination'] = $contract['grades_course_paid_nums'];
				$contract_data['stay_amount']  = $stay_amount_money; //欠费
				$contract_data['amount'] = $amount_money;  //报读项目收费
				$contract_data['net_receipts'] = $net_receipts;  //实际收费
				$contract_data['total_amount'] = $total_amount_money;  //应收
				$contract_data['expenditure'] = $expenditure_money;  //课消
				$contract_data['balance'] = $payment_money_balance;  //学费余额(不包含物品费用)
				$contract_data['storedvalue'] = $storedvalue;  //储值

				//更新学生储蓄账户
				$student_result = (new StudentModel())->get(['id' => $contract['student_id']]);
				//更新欠费状态
				if($contract_data['balance'] >= 0){
					(new StudentModel())->where(['id' => $contract['student_id']])->update(['arrears_status' => 1]);
				}else if($contract_data['balance'] < 0){
					(new StudentModel())->where(['id' => $contract['student_id']])->update(['arrears_status' => 0]);
				}
				//选择教务
				if($params['eduadmin_id'] != -1){
					(new StudentModel())->where(['id' => $contract['student_id']])->update(['user_edu_id' => $params['eduadmin_id']]);
				}
				$srudent_item['storedvalue'] = $student_result['storedvalue'] + $des_storedvalue;
				(new StudentModel())->save(['storedvalue' => $srudent_item['storedvalue']],['id' => $contract['student_id']]);

				if($contract_data['stay_amount'] > 0){
					$contract_data['status'] = 3;//订单状态：部分收款订单
				}else{
					$contract_data['status'] = 1;//订单状态：已收款订单
				}
				// 更新已报课程状态
				(new CourseLogModel())->save(['status' => $contract_data['status']], ['contract_number' => $contract['contract_number']]);
				// 订单收款流水
				CommonService::writeFlowRecord($contract['contract_number'], 1, $params['amountcollected']*100, '记录订单收款流水',$receivables['campus_id'],$receivables['receipt_number'],$receivables['payment_method']);
				//校区业绩
				$checkCampus = (new AllocationCampusModel())->get(['receipt_number'=>$params['receipt_number']]);
				if($checkCampus){
					(new AllocationCampusModel())->where(['receipt_number'=>$params['receipt_number']])->update(['status'=>2]);
				}
				//个人业绩
				$checkOnly = (new AllocationOnlyModel())->get(['receipt_number'=>$params['receipt_number']]);
				if($checkOnly){
					(new AllocationOnlyModel())->where(['receipt_number'=>$params['receipt_number']])->update(['status'=>2]);
				}

			}elseif($receivables['payment_method'] == '115'){
//				$this->data = (new XcxpayService($this->type))->executionPayment($params);
				$params['user_id'] = xcxapi_get_current_user_id();
				$res = (new WxpayService())->xcxsmPay($params,2);
				if ('SUCCESS' === $res['result_code'] && 'SUCCESS' === $res['return_code'] && 'OK' === $res['return_msg']) {
					// 自定义二维码配置
					$config = [
						'title' => true,
						'title_content' => '校务帮',
						'logo' => true,
						'logo_url' => './education/images/wechat.jpg',
						'logo_size' => 80,
					];

					// 直接输出
					$qr_url = $res['code_url'];
					$qr_code = new QrcodeServer($config);
					$qr_img = $qr_code->createServer($qr_url);
					$imageString = base64_encode($qr_img);
					$this->data['img'] = 'data:image/jpg;base64,'.$imageString;
				} else {
					$this->error($res['msg'], null, '', 1);
				}
			}
			//更新订单支付方式
			$contract_data['pay_type'] = $receivables['payment_method'];
			(new ContractModel())->save($contract_data, ['id' => $params['contract_id']]);
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
	}
	
	/**
	 * 添加试听学员
	 * User: chenben
	 * Date: 2020/04/03
	 *
	 * @param $params
	 * @return array
	 */
	public function addAudition($params)
	{
		try {
			$class_ids = $params['class_ids']; //课节ID
			$class_id_str = implode(',',$class_ids);
			$class_grades_names = array_unique((new GradesDetailsListsModel())->where(['id' => ['in',$class_id_str]])->column('class_grades_name'));
			$class_manage_id_room_str = implode(',',$class_grades_names);
            $student_id = $params['student_id']; //学生ID
			$class_ids_arr = $class_ids; //课节ID
			(new StudentModel())->where(['id' => $student_id])->update(['is_audition' => 0, 'follow_up' => 35]);  //状态变为已跟进
			$student_add_arr =[]; //添加学生
			$grades_id = []; //班级ID
			$audition_add_arr = []; //试听管理
			$student_add_Infos_arr =[]; //添加学生上课信息
            $res = (new StudentModel())->get(['id' => $student_id]);
            for($l=0; $l<count($class_ids_arr); $l ++){
                $nums = (new AuditionModel())->where(['student_id' => $student_id, 'campus_id' => $res['campus_id'], 'class_id' => $class_ids_arr[$l]])->count();
                if($nums > 0){
                  continue;
                }
                $item_auditon=[];
                $item_auditon['student_id'] = $student_id; //学生ID
                $item_auditon['campus_id'] = $res['campus_id']; //校区ID
                $item_auditon['class_id'] = $class_ids_arr[$l]; //课节ID
                $audition_add_arr[] = $item_auditon;
            }
			if(count($audition_add_arr) > 0){
                if(!(new AuditionModel())->saveAll($audition_add_arr)){
                    $this->error('添加学员试听课节信息失败', null, -1, 1);
                }
            }
			for($j=0;  $j<count($class_ids_arr); $j ++){
                $infos_result = (new GradesDetailsListsModel())->get(['id' => $class_ids_arr[$j]]);
                $grades_id[] = $infos_result['class_manage_id'];  //班级ID
                $students_result = (new StudentModel())->get(['id' => $student_id]);
                $item =[];
                $item['class_subject_id'] = $infos_result['class_manage_id']; //分班ID
                $item['student_id'] = $student_id;  //学生ID
                $item['campus_id'] = $students_result['campus_id']; //校区ID
                $item['student_name'] = $students_result['name']; //学生姓名
                $item['contract_number'] = '---'; //合同编号
                $item['status'] = 3; //试听分配
                $item['student_type'] = 4; //试听学员
                $item['room_id'] = $infos_result['class_room_id']; //教室ID
                (new GradesDetailsModel())->where(['id' => $infos_result['class_manage_id']])->update(['status' => 1]);
                $student_add_arr[] = $item;

              
                $count_num = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $class_ids_arr[$j],'student_id' => $student_id, 'report_status' => 3])->count();
                if($count_num > 0){
                     continue;
                }

                $item_infos = [];
                $item_infos['class_manage_details_id'] =  $class_ids_arr[$j]; //节课ID
                $item_infos['class_subject_id'] = $infos_result['class_manage_id']; //分班ID
                $item_infos['campus_id'] =  $infos_result['campus_id']; //校区ID
                $item_infos['student_id'] = $student_id;//学生ID
                $item_infos['student_name']  =  $students_result['name']; //学生姓名
                $item_infos['room_name'] = $infos_result['class_room']; //教室名称
                $item_infos['weekday'] =  $infos_result['weekday']; //星期
                $item_infos['class_date'] = $infos_result['class_date']; //开课日期
                $item_infos['course_id'] = $infos_result['course_id']; //课程ID
                $item_infos['report_status'] = 3;  //试听
                $item_infos['operatorer'] = xcxapi_get_current_name();  //操作人

                if($students_result['is_audition'] == 0){    //试听
                     $item_infos['contract_number'] = '---';
                }


                $item_infos['room_id'] = $infos_result['class_room_id'];//教室ID
                $start = strtotime($infos_result['class_subject_start']);  //开始时间
                $end = strtotime($infos_result['class_subject_end']);  //结束时间
                $item_infos['duration'] = ceil(($end - $start)/60); //时长
                $student_add_Infos_arr[] = $item_infos;
            }
			if(count($student_add_Infos_arr) > 0){
                if(!((new StudentSubjectInfosClassModel()))->saveAll($student_add_Infos_arr)){
                    $this->error('添加学员课节信息失败', null, -1, 1);
                }
            }
            if(count($student_add_arr) > 0){
                if(!(new StudentSubjectClassModel())->saveAll($student_add_arr)){
                    $this->error('添加学员列表失败', null, -1, 1);
                }
            }
            //计算学生在该试听班级课节总数
            $grades_id = array_unique($grades_id);  //去重
            for($f = 0; $f < count($grades_id); $f ++){
                $count = (new StudentSubjectInfosClassModel())->where(['student_id' => $student_id, 'class_subject_id' => $grades_id[$f], 'report_status' => 3])->count();
				(new StudentSubjectInfosClassModel())->where(['student_id' => $student_id, 'class_subject_id' => $grades_id[$f], 'report_status' => 3])->update(['surplus_class_elimination' => $count]);
                
            }

			$student_name = (new StudentModel())->get($student_id)['student_name'];
			CommonService::writeFollowUpLog($student_id, xcxapi_get_current_user_id(), $res['campus_id'], 1, xcxapi_get_current_name().' '.'新增试听学员'.' '.$student_name.'且试听班级为'.$class_manage_id_room_str, 1, 35);
            
			
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
	}

	/**
	 * 储值
	 * User: chenben
	 * Date: 2020/03/31
	 *
	 * @param $params
	 * @return array
	 */
	public function storedValue($params)
	{
		try {
            //生成储值订单
            $data['storedvalue'] = $params['amountcollected'] * 100;  //储值金额
            $data['campus_id'] = $params['campus_id']; //校区
            $data['student_id'] = $params['student_id'] ; //学生ID
			$data['out_remark'] = $params['remark']; //储值备注
            $student_table = (new StudentModel())->get(['id' => $params['student_id']]);
			$data['contractor'] = $student_table['user_id']; //签约人
			   /*录入类型，如果存在该生合同则为老生，否则为新生*/
            $res = (new ContractModel())->get(['student_id' => $params['student_id']]);
            if(!$res){
                $input_type = 0;
            }else{
                $input_type = 1;
            }
            $data['input_type'] = $input_type; //录入类型
            $data['student_name'] = $student_table['student_name']; ; //学生姓名
            $data['signing_date'] = $params['signing_date'] ; //签约日期
            $data['signing_type'] = 114 ; //签约类型【储值新签】
            $data['payee'] = $params['payee_id'] ; //收款人
		//	$data['status'] = -2 ; //-2：已生成储值单未支付，-1：已生成储值单已支付'
			$data['status'] = 1;
            $data['contract_number'] = CommonService::generateNumber().'-CZ' ; //合同编号

            //生成储值订单
            if(!(new ContractModel())->save($data)){
                $this->error('生成储值订单失败', null, '', 1);
            }
			$contract_number_id = (new ContractModel())->get(['contract_number' => $data['contract_number']])['id'];
			$receivables['contract_number'] = $data['contract_number'];
			$receivables['paydate'] = date('Y-m-d');
			$receivables['payee'] = $data['payee'];
			$receivables['flow_number'] = 'LSH'.date('md').$contract_number_id;
			$receivables['amount'] = $data['storedvalue'];
			$receivables['campus_id'] = $data['campus_id'];
			$receivables['receipt_number'] = $params['receipt_number'];
			$receivables['payment_method'] = $params['pay_type_id'];
			//收款管理写入
			$res = (new ReceivablesModel())->save($receivables);

            //更新学生储蓄账户
            $student_result = (new StudentModel())->get(['id' => $data['student_id']]);
            $srudent_item['storedvalue'] = $student_result['storedvalue'] + $data['storedvalue'];
            if(!(new StudentModel())->save(['storedvalue' => $srudent_item['storedvalue'], 'is_audition' => 2, 'sign_up' => 1],['id' => $data['student_id']])){   //储值后默认转为学员
                $this->error('更新储值账户失败', null, '', 1);
            }

			$campus_achievement= [];  //校区业绩
			$only_achievement= [];  //个人业绩
			if (count($params['campus_achievement_list']) > 0) {    //校区业绩
                for ($i = 0; $i < count($params['campus_achievement_list']); $i++) {
                    $item = $params['campus_achievement_list'][$i];
					if($item['campus_id'] != null && $item['department_id'] != null){
						$cell_all = [];
						$cell_all['contract_number'] =  $data['contract_number'];
						$cell_all['campus_id_all'] = $item['campus_id'];
						$cell_all['campus_id_all_text'] = $item['campus_name'];
						$cell_all['assignment_all'] = $item['department_id'];
						$cell_all['assignment_all_text'] = $item['department_name'];
						$cell_all['rate_all'] = $item['rate'];
						$cell_all['receipt_number'] = $params['receipt_number'];
						$cell_all['operator'] = xcxapi_get_current_user_id();
						$cell_all['rate_all_money'] = round(($data['storedvalue'] * ($item['rate'] / 100)));
						$cell_all['amount_already_all'] = $data['storedvalue'];
						$campus_achievement[] = $cell_all;
					}
                }
            }
			
			if (count($params['only_achievement_list']) > 0) {    //个人业绩
                for ($i = 0; $i < count($params['only_achievement_list']); $i++) {
                    $item = $params['only_achievement_list'][$i];
					if($item['only_id'] != null && $item['department_id'] != null){
						$cell_all = [];
						$cell_all['contract_number'] =  $data['contract_number'];
						$cell_all['payee_only'] = $item['only_id'];
						$cell_all['payee_only_text'] = $item['only_name'];
						$cell_all['assignment_only'] = $item['department_id'];
						$cell_all['assignment_only_text'] = $item['department_name'];
						$cell_all['rate_only'] = $item['rate'];
						$cell_all['receipt_number'] = $params['receipt_number'];
						$cell_all['operator'] = xcxapi_get_current_user_id();
						$cell_all['rate_only_money'] = round(($data['storedvalue'] * ($item['rate'] / 100)));
						$cell_all['amount_already_only'] = $data['storedvalue'];
						$only_achievement[] = $cell_all;
					}
                }
            }
			
			if(count($campus_achievement) > 0 ){
                if(!(new AllocationCampusModel())->saveAll($campus_achievement)){
                    $this->error('插入校区业绩信息失败', null, '', 1);
                }
            }

            if(count($only_achievement) > 0 ){
                if(!(new AllocationOnlyModel())->saveAll($only_achievement)){
                    $this->error('插入个人业绩信息失败', null, '', 1);
                }
            }
			if($params['pay_type_id'] == '79'){
				// 订单收款流水
				CommonService::writeFlowRecord($data['contract_number'], 1, $data['storedvalue'], '记录订单储值流水',$data['campus_id'],$params['receipt_number'],$params['pay_type_id']);
				//校区业绩
				$checkCampus = (new AllocationCampusModel())->get(['receipt_number'=>$params['receipt_number']]);
				if($checkCampus){
					(new AllocationCampusModel())->where(['receipt_number'=>$params['receipt_number']])->update(['status'=>2]);
				}
				//个人业绩
				$checkOnly = (new AllocationOnlyModel())->get(['receipt_number'=>$params['receipt_number']]);
				if($checkOnly){
					(new AllocationOnlyModel())->where(['receipt_number'=>$params['receipt_number']])->update(['status'=>2]);
				}
			}elseif($params['pay_type_id'] == '115'){
				$params['user_id'] = xcxapi_get_current_user_id();
				$res = (new WxpayService())->xcxsmPay($params,1);
				if ('SUCCESS' === $res['result_code'] && 'SUCCESS' === $res['return_code'] && 'OK' === $res['return_msg']) {
					// 自定义二维码配置
					$config = [
						'title' => true,
						'title_content' => '校务帮',
						'logo' => true,
						'logo_url' => './education/images/wechat.jpg',
						'logo_size' => 80,
					];

					// 直接输出
					$qr_url = $res['code_url'];
					$qr_code = new QrcodeServer($config);
					$qr_img = $qr_code->createServer($qr_url);
					$imageString = base64_encode($qr_img);
					$this->data['img'] = 'data:image/jpg;base64,'.$imageString;
				} else {
					$this->error($res['msg'], null, '', 1);
				}
			}
		
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
	}

    /**
     * 新增客户
     * User: wufeng
     * Date: 2019/5/24.
     *
     * @param $params
     *
     * @return array
     */
    public function addCustomer($params)
    {
        try {
            if (!$this->customerValidate->scene('addCustomer')->check($params)) {
                throw new BaseException($this->customerValidate->getError(), 'PARAM_ERROR');
            }
            $data = [];
            $data['phone'] = $params['phone'];
            $data['campus_id'] = $params['campus_id'];
            if (0 === (int) $params['user_id']) {
                $data['course_consultant_type'] = 2; //公海
                $data['course_consultant'] = '公海';
                $data['user_id'] = 0;
            } else {
                $data['course_consultant_type'] = 1; //自己
                $data['user_id'] = $params['user_id'];
                $data['course_consultant'] = (new UserModel())->get($params['user_id'])['name'];
            }
            $data['intentional_grade'] = $params['intentional_grade'];
            $data['is_audition'] = 1;
            $data['channel'] = $params['channel'] ? $params['channel'] : 0;
            $data['sex'] = $params['sex'];
            $data['remark'] = $params['remark'];
            $data['student_name'] = $params['student_name'];
            $data['name'] = $params['student_name'];
            $data['student_number'] = CommonService::generateStudentNumber();  //学号
            $data['address'] = $params['address'];
            $data['grade'] = $params['grade'];
            $data['birth'] = $params['birth'] ? $params['birth'] : null;
            $data['school_class'] = $params['school_class'];
            $data['weixin'] = $params['weixin'];
            $data['guardian'] = $params['guardian'];
            $data['guardian_phone'] = $params['guardian_phone'];
            $data['register_date'] = date('Y-m-d');
            $data['follow_up'] = 34;
            Db::name('edu_student')->insert($data);
            $id = Db::name('edu_student')->getLastInsID();

			$check = (new ParentInformationModel())->get(['student_id'=>$id,'username'=>$params['guardian_phone']]);
			if($check){
				throw new BaseException('监护人手机号已存在');
			}

            //家长信息写入 开始
            $parentInformation = [];
            $parentInformation['student_id'] = $id; //学员ID
			$parentInformation['campus_id'] = $data['campus_id'];//校区ID
            $parentInformation['name'] = $data['guardian']; //姓名
            $parentInformation['username'] = $data['guardian_phone']; //手机号码
            $parentInformation['salt'] = md5(date('Y-m-d H:i:s'));
            $parentInformation['password'] = AccountService::encodePassword(123456, $parentInformation['salt']); //密码
            $parentInformation['img'] = '/img.jpg'; //头像
            $parentInformation['status'] = 1; //状态：1启用 0禁用
            (new ParentInformationModel())->save($parentInformation);
            //家长信息写入 结束

            // 学员客户跟进沟通记录写入
            //	CommonService::writeFollowUpLog($id, $data['campus_id'], 1, xcxapi_get_current_name().' '.'添加了客户'.' '.$data['student_name'], 1,
            CommonService::writeFollowUpLog($id, $data['user_id'], $data['campus_id'], 1, xcxapi_get_current_name().' '.'添加了客户'.' '.$data['student_name'], 1, $data['follow_up']);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 客户详情、客户跟进记录
     * User: wufeng
     * Date: 2019/5/27.
     *
     * @param $params
     *
     * @return array
     */
    public function customerDetail($params)
    {
        try {
            $where = [];
			//按手机号、姓名、顾问搜索
			if (isset($params['word']) && '' !== $params['word']) {
				$where['content'] = ['like', '%'.$params['word'].'%'];
			}
            $where['student_id'] = $params['id'];
            $this->data['log'] = (new FollowUpLogModel())
                ->where($where)
                ->order('time desc')
                ->select()
                ->toArray()
            ;
            foreach ($this->data['log'] as &$log) {
                if (1 === (int) $log['type']) {
                    $log['type_text'] = '系统';
                    $log['avatar'] = '/img.jpg';
                } elseif (2 === (int) $log['type']) {
                    $log['type_text'] = xcxapi_get_current_name();
                    $log['avatar'] = xcxapi_get_current_img();
                }
                $log['follow_up'] = DictionaryModel::getById($log['follow_up'], 'name');
                $log['mode'] = DictionaryModel::getById($log['mode'], 'name');
                if ($log['intentional_grade'] < 3) {
                    $log['intentional_grade_text'] = '低';
                } elseif ($log['intentional_grade'] > 3) {
                    $log['intentional_grade_text'] = '高';
                } else {
                    $log['intentional_grade_text'] = '中';
                }
                $log['marks'] = (new MarkingModel())->where(['lid' => $log['id']])->select();
            }
            $this->data['detail'] = (new StudentModel())
                ->where(['id' => $params['id']])
                ->find()
            ;
            $this->data['detail']['channel_text'] = DictionaryModel::getById($this->data['detail']['channel'], 'name');
            $this->data['detail']['follow_up_text'] = DictionaryModel::getById($this->data['detail']['follow_up'], 'name');
            $this->data['detail']['grade_text'] = DictionaryModel::getById($this->data['detail']['grade'], 'name');
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 试听班级列表
     * User: wufeng
     * Date: 2019/6/3.
     *
     * @param $params
     *
     * @return array
     */
    public function auditionClassList($params)
    {
        try {
            $page = isset($params['page']) ? (int) $params['page'] : 1;
            $limit = isset($params['limit']) ? (int) $params['limit'] : 10;

            if (isset($params['word']) && '' !== $params['word']) {
                $where['b.teacher|b.class_grades_name|b.class_room'] = ['like', $params['word'].'%'];
            }
            //时间段
            if (isset($params['start_date']) && '' !== $params['start_date'] && isset($params['end_date']) && '' !== $params['end_date']) {
                $where['class_date'] = ['between', [$params['start_date'], $params['end_date']]];
            }
            $where = [];
            $this->data = (new TimetableModel())->alias('a')
                ->join('edu_class_manage_details b', 'b.id = a.class_manage_id')
                ->where($where)
                ->order('id desc')
                ->paginate($limit, false, ['page' => $page])
                ->toArray()
            ;
            foreach ($this->data as $item) {
                $item['grades_course_class_name'] = $item['grades_name'].'('.$item['course_class_name'].')';
                $item['grades_time'] = $item['class_date'].'---'.$item['class_subject_start'].'-'.$item['class_subject_end'];
                $item['student_nums'] = $item['preoccupation'];
                $result = (new StudentSubjectClassModel())->where(['class_subject_id' => $item['class_manage_id']])->select();
                $student_id_arr = [];
                $nums = 0;
                foreach ($result as $key => $value) {
                    if (!\in_array($value['student_id'], $student_id_arr, true)) {
                        $nums = $nums + 1;
                        $student_id_arr[] = $value['student_id'];
                    }
                }

                if (0 === (int) $item['student_nums']) {
                    $item['student_nums'] = $nums.'/'.'不限';
                } else {
                    $item['student_nums'] = $nums.'/'.$item['student_nums'];
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 收费
     * User: wufeng
     * Date: 2019/6/12.
     *
     * @param $params
     *
     * @return array
     */
    public function charge($params)
    {
        try {
            $data = [];
            $data['phone'] = $params['phone'];
            $data['student_name'] = $params['student_name'];
            $data['student_id'] = $params['student_id'];
            if (isset($params['project_type']) && !empty($params['project_type'])) {
                if (1 === $params['project_type'] && 2 === $params['project_type']) {
                } elseif (1 === $params['project_type']) {
                } elseif (2 === $params['project_type']) {
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 到访试听
     * User: wufeng
     * Date: 2019/12/31.
     *
     * @param $params
     *
     * @return array
     */
    public function visit($params)
    {
        try {
            if ('audition' === $params['table_type']) {
                $where = [];
				$where['a.campus_id'] = ['in',xcxapi_get_current_campus_id()];
                //按手机号、姓名搜索
                if (isset($params['word']) && '' !== $params['word']) {
                    $where['s.phone|s.student_name|s.name'] = ['like', '%'.$params['word'].'%'];
                }
				if (isset($params['sign_status']) && '' !== $params['sign_status']) {
					if(1 === (int) $params['sign_status']){
						$where['a.sign_status'] = 0;
					}elseif (2 === (int) $params['sign_status']){
						$where['a.sign_status'] = 1;
					}
				}
				if (isset($params['follow_up']) && '' !== $params['follow_up']) {
					$where['s.follow_up'] = $params['follow_up'];
				}
                $order = 'a.sign_status desc';
                $this->data = (new AuditionModel())->alias('a')
                    ->join(['edu_student' => 's'], 's.id = a.student_id')
                    ->where($where)
                    ->order($order)
                    ->select()
                    ->toArray()
                ;
                foreach ($this->data as &$val) {
                    $val['follow_up_text'] = DictionaryModel::getById($val['follow_up'], 'name');
                    if (0 === (int) $val['sign_status']) {
                        $val['sign_status_text'] = '未签到';
                    } elseif (1 === (int) $val['sign_status']) {
                        $val['sign_status_text'] = '已签到';
                    }
                }
            } elseif ('door' === $params['table_type']) {
                $where_door = [];
				if(5 === (int) xcxapi_get_current_wtype()){
					$where_door['user_id'] = xcxapi_get_current_user_id();
				}else{
					$where_door['campus_id'] = ['in',xcxapi_get_current_campus_id()];
				}
                //按手机号、姓名搜索
                if (isset($params['word']) && '' !== $params['word']) {
                    $where_door['phone|student_name|name'] = ['like', '%'.$params['word'].'%'];
                }
                $where_door['follow_up'] = ['in', '103,36']; //已上门，已预约
                $this->data = (new StudentModel())
                    ->where($where_door)
					->order('id desc')
                    ->select()
                    ->toArray()
                ;
                foreach ($this->data as &$val) {
                    $val['follow_up_text'] = DictionaryModel::getById($val['follow_up'], 'name');
                    if ('--' !== $val['visiting_date'] && null !== $val['visiting_date']) {
                        $val['visiting_text'] = '已到访';
                        $val['visiting'] = 1;
                    } else {
                        $val['visiting_text'] = '未到访';
                        $val['visiting'] = 2;
                    }
                }
            }
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 签到
     * User: wufeng
     * Date: 2020/01/06.
     *
     * @param $params
     *
     * @return array
     */
    public function signStatus($params)
    {
        try {
            $sign = (new AuditionModel())->where(['student_id' => $params['student_id']])->find();
            if (1 === (int) $sign['sign_status']) {
                $data['sign_status'] = 0; //未签到
            } else {
                $data['sign_status'] = 1; //已签到
            }
            (new AuditionModel())->save($data, ['student_id' => $params['student_id']]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 到访
     * User: wufeng
     * Date: 2020/01/06.
     *
     * @param $params
     *
     * @return array
     */
    public function visitStatus($params)
    {
        try {
            $data = [];
            if (2 === (int) $params['visiting']) {
                $data['visiting_date'] = $params['date'];
            } elseif (1 === (int) $params['visiting']) {
                $data['visiting_date'] = '--';
            }
            (new StudentModel())->save($data, ['id' => $params['id']]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 跟进
     * User: wufeng
     * Date: 2020/01/04.
     *
     * @param $params
     *
     * @return array
     */
    public function followUpLists($params)
    {
        try {
            $where = [];
			//按手机号、姓名、顾问搜索
			if (isset($params['word']) && '' !== $params['word']) {
				$where['phone|student_name|name|course_consultant'] = ['like', '%'.$params['word'].'%'];
			}
			//客户状态
			if (isset($params['follow_up']) && '' !== $params['follow_up']) {
				$where['follow_up'] = $params['follow_up'];
			}
            $order = 'id desc';
            $time = '';
            switch ($params['table_type']) {
                case 'today':
                    //今天待跟进
                    $where['next_follow_up_record'] = date('Y-m-d');

                    break;
                case 'tomorrow':
                    // 明天待跟进
                    $where['next_follow_up_record'] = $date = date('Y-m-d', strtotime('+1 day'));

                    break;
                case 'week':
                    //本周待跟进
                    $time = 'week';

                    break;
            }
            $where['status'] = 1;
			if(5 === (int) xcxapi_get_current_wtype()){
				$where['user_id'] = xcxapi_get_current_user_id();
			}else{
				$where['campus_id'] = ['in',xcxapi_get_current_campus_id()];
			}

            if ($time) {
                $this->data = (new StudentModel())
                    ->where($where)
                    ->whereTime('next_follow_up_record', $time)
                    ->order($order)
                    ->select()
                    ->toArray()
                ;
            } else {
                $this->data = (new StudentModel())
                    ->where($where)
                    ->order($order)
                    ->select()
                    ->toArray()
                ;
            }

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
            foreach ($this->data as &$val) {
                $val['follow_up_text'] = DictionaryModel::getById($val['follow_up'], 'name');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 释放客户到公海
     * User: wufeng
     * Date: 2020/01/09.
     *
     * @param $params
     *
     * @return array
     */
    public function releaseCustomer($params)
    {
        try {
            (new StudentModel())->save(['course_consultant_type' => 2, 'course_consultant' => '公海', 'user_id' => 0], ['id' => $params['id']]);
            // 学员客户跟进沟通记录写入
            $student = (new StudentModel())->get($params['id']);
            CommonService::writeFollowUpLog($params['id'], 140, $student['campus_id'], 1, get_current_name().' '.'将客户'.' '.$student['student_name'].' '.'释放到了公海', 1, $student['follow_up']);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/01/09.
     *
     * @param $params
     *
     * @return array
     */
    public function invalid($params)
    {
        try {
            $student = (new StudentModel())->get($params['id']);
            (new AuditionModel())->save(['status' => 0], ['student_id' => ['in', $params['id']]]);  //试听记录转为无效
            //follow_up:33 未分配
            (new StudentModel())->save(['follow_up' => 33,  'course_consultant_type' => 0, 'course_consultant' => '-', 'status' => 2, 'reason' => $params['reason'], 'user_id' => 0], ['id' => $params['id']]);
            CommonService::writeFollowUpLog($params['id'], 140, $student['campus_id'], 1, 'system'.' '.'将客户'.' '.$student['student_name'].' '.'的状态修改为无效'.'<br/>'.'标记原因：'.$params['reason'], 1, $student['follow_up']);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 转给同事
     * User: wufeng
     * Date: 2020/01/09.
     *
     * @param $params
     *
     * @return array
     */
    public function revolveColleague($params)
    {
        try {
            $name = (new UserModel())->get(['id' => $params['user_id']])['name'];
            (new StudentModel())->save(['course_consultant_type' => 1, 'campus_id' => input('campus_id'),  'user_id' => $params['user_id'], 'course_consultant' => $name], ['id' => $params['id']]);
            // 学员客户跟进沟通记录写入
            $student = (new StudentModel())->get($params['id']);
            CommonService::writeFollowUpLog($params['id'], 140, 1, 1, 'system'.' '.'将客户'.' '.$student['student_name'].' '.'转给了同事'.' '.$name, 1, $student['follow_up']);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 移除客户
     * User: wufeng
     * Date: 2020/01/09.
     *
     * @param $params
     *
     * @return array
     */
    public function delete($params)
    {
        try {
            (new StudentModel())->where(['id' => $params['id']])->delete();
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	/**
     * 签约类型
     * User: chenben
     * Date: 2020/03/28.
     *
     * @param $params
     *
     * @return array
     */
    public function getContractType($params)
    {
        try {
            $this->data = (new DictionaryModel())->where(['type' => 32])->select()->toArray();
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	/**
     * 创建订单
     * User: chenben
     * Date: 2020/03/29.
     *
     * @param $params
     *
     * @return array
     */
    public function createOrder($params)
    {
        try {
			//创建订单
			//生成订单号
			$ContractModel = new ContractModel();
			$ContractModel->save(['contract_number' => $this->generateNumber()]);
			$contract_id = $ContractModel->id;
			$res_student = (new StudentModel())->get(['id' => $params['student_id']])->toArray();
			if($params['deduction_type'] == 1){ //抵扣
				$stay_amount = ($params['order_receivable'] - ($res_student['storedvalue'] / 100));
				if($stay_amount <= 0){
					$data['stay_amount'] = 0; 
					$data['storedvalue'] = -($params['order_receivable'] * 100);
				}else{
					$data['stay_amount'] = $stay_amount * 100;
					$data['storedvalue'] = -($res_student['storedvalue']);
				}
			}else if($params['deduction_type'] == 2){ //非抵扣
				$data['storedvalue']  = 0;
				$data['stay_amount'] = $params['order_receivable'] * 100;
			}
				

            $data['total_amount'] = ($params['order_money'] - $params['order_discount']) * 100;
            $data['preferential'] = $params['order_discount'] * 100;
            $data['direct_discount'] = $params['directmoneyall'] * 100;  //直减优惠
			$data['net_receipts'] = abs($data['storedvalue']); //实收款
            $data['amount'] =  $data['net_receipts']; //项目总收款
			
			$pro_data = $params['pro_data'];
			
			//校区
			$campus_id = 1; //前端选择校区
			
			//存入报读项目关联表
			$good_data = [];
			$course_data = [];
			$grades_data = [];
			
			//课程部分
			$courseIds = [];
            $courseNums = [];
            $courseNums_Give = [];
			$courseNums_Pay = [];
			//班级部分
			$grades_courseIds = [];
            $grades_courseNums = [];
            $grades_courseNums_Give = [];
			$grades_courseNums_Pay = [];
			
			//分摊
			$Total_assessed_amount = 0;
			foreach ($pro_data as &$item) {
				if($item['assessed_status'] == 1){ //已分摊
					$Total_assessed_amount = $Total_assessed_amount + $item['rate_money'] * 100;
				}
			}
			
			foreach ($pro_data as &$item) {
				if($item['type_pro'] == 1){  //物品
					$item_goods = [];
					$item_goods['student_id'] = $params['student_id']; //学生ID
					$item_goods['goods_id'] = $item['id']; //物品ID
					$item_goods['price'] = $item['unit_price'] * 100;
                    $item_goods['total_price'] = $item['unit_price'] * $item['buy_num'] * 100;
                    $item_goods['net_receipts'] = $item['rate_money'] * 100;
					$item_goods['goods_num'] = $item['buy_num'];
					$item_goods['contract_type'] = $item['contract_Type_id'];
					$item_goods['assessed_status'] = $item['assessed_status'];
					if($item_goods['assessed_status'] == 1){
						$item_goods['assessed_amount'] = round(($item_goods['net_receipts'] / $Total_assessed_amount) * $data['preferential']); //四舍五入取整
					}
					$item_goods['direct_money'] = $item['directmoney'] * 100;
					$item_goods['campus_id'] = $campus_id;  //合同校区
					$item_goods['contract_id'] = $contract_id;
                    $good_data[] = $item_goods;
					
				}else if($item['type_pro'] == 2){ //课程
				
					$item_course = [];
					$item_course['student_id'] = $params['student_id']; //学生ID
					$item_course['course_id'] = $item['id']; //课程ID
					$item_course['price'] = $item['unit_price'] * 100;
                    $item_course['total_price'] = $item['unit_price'] * $item['buy_num'] * 100;
					$item_course['net_receipts'] = $item['rate_money'] * 100;
					$item_course['class_num'] = $item['buy_num'];
					$item_course['contract_type'] = $item['contract_Type_id'];
					$item_course['assessed_status'] = $item['assessed_status'];
					if($item_course['assessed_status'] == 1){
						$item_course['assessed_amount'] = round(($item_course['net_receipts'] / $Total_assessed_amount) * $data['preferential']); //四舍五入取整
					}
					$item_course['direct_money'] = $item['directmoney'] * 100;
					$item_course['campus_id'] = $campus_id;  //合同校区
					$item_course['contract_id'] = $contract_id;
					$item_course['give_class_num'] = $item['give_num'];
					$course_data[] = $item_course;
					
					$courseIds[] = $item_course['course_id'];
					$courseNums[] = $item_course['class_num'];
					$courseNums_Give[] = $item_course['give_class_num'];
					$courseNums_Pay[] = 0;
					
				}else if($item['type_pro'] == 3){ //班级
				
					$item_grades = [];
					$item_grades['student_id'] = $params['student_id']; //学生ID
					$item_grades['grades_id'] = $item['id']; //班级ID
					$item_grades['course_id'] = $item['course_id']; //课程ID
					$item_grades['price'] = $item['unit_price'] * 100;
                    $item_grades['total_price'] = $item['unit_price'] * $item['buy_num'] * 100;
					$item_grades['net_receipts'] = $item['rate_money'] * 100;
					$item_grades['class_num'] = $item['buy_num'];
					$item_grades['contract_type'] = $item['contract_Type_id'];
					$item_grades['assessed_status'] = $item['assessed_status'];
					if($item_grades['assessed_status'] == 1){
						$item_grades['assessed_amount'] = round(($item_grades['net_receipts'] / $Total_assessed_amount) * $data['preferential']); //四舍五入取整
					}
					$item_grades['direct_money'] = $item['directmoney'] * 100;
					$item_grades['campus_id'] = $campus_id;  //合同校区
					$item_grades['contract_id'] = $contract_id;
					$item_grades['give_class_num'] = $item['give_num'];
					$grades_data[] = $item_grades;
					
					$grades_courseIds[] = $item_grades['course_id'];
					$grades_courseNums[] = $item_grades['class_num'];
					$grades_courseNums_Give[] = $item_grades['give_class_num'];
					$grades_courseNums_Pay[] = 0;
					
				}
			}
			
			$data['course'] = implode(',', $courseIds);
            $data['course_nums'] = implode(',', $courseNums);
            $data['give_course_nums'] = implode(',', $courseNums_Give);
            // 剩余课时
			$data['course_elimination'] =  implode(',', $courseNums_Pay);
            $count = count($courseIds);
            $arr = '';
            for ($i = 0; $i < $count; ++$i) {
                $arr .= '0'.',';
            }
            $arr = substr($arr, 0, strlen($arr) - 1);
            $data['course_paid_nums'] = $arr;
			
			
			$data['grades_course'] = implode(',', $grades_courseIds);
            $data['grades_course_nums'] = implode(',', $grades_courseNums);
            $data['give_grades_course_nums'] = implode(',', $grades_courseNums_Give);
            // 剩余课时
			$data['grades_course_elimination'] = implode(',', $grades_courseNums_Pay);

            $count = count($grades_courseIds);
            $arr = '';
            for ($i = 0; $i < $count; ++$i) {
                $arr .= '0'.',';
            }
            $arr = substr($arr, 0, strlen($arr) - 1);
            $data['grades_course_paid_nums'] = $arr;
			

            $data['student_name'] = $res_student['student_name'];
            $data['grade'] = $res_student['grade'];
            $data['school_class'] = $res_student['school_class'];
			$data['real_rate'] = $params['real_rate']; //真实折扣率
			$data['discount_modle'] = $params['discount_modle']; //折扣模式
			$data['discount_rate'] = $params['ratemoneyall']; //折扣比率
			$data['campus_id'] = $campus_id; //校区ID
			$data['student_id'] = $res_student['id']; //学生ID
			$data['out_remark'] = $params['out_remarks']; //对外备注
			$data['in_remark'] = $params['in_remarks']; //对内备注
			$data['input_type'] = $params['input_type']; //录入类型
			$data['signing_date'] = $params['signing_date']; //签约日期
			$data['contractor'] = $params['contractor']; //签约人
			$data['payee'] = xcxapi_get_current_user_id(); //收款人
	
			$student_item['storedvalue'] = $res_student['storedvalue'] + $data['storedvalue'];
            (new StudentModel())->save(['storedvalue' => $student_item['storedvalue']],['id' => $res_student['id']]);
	
			//创建订单
			$ContractModel->save($data, ['id' => $contract_id]);
			
			//生成-物品-课程-班级子订单
			
			//物品
			(new GoodsContractModel())->saveAll($good_data);
			//课程
			(new CourseContractModel())->saveAll($course_data);
			//班级
			(new GradesContractModel())->saveAll($grades_data);
			
			 //查询当前订单编号
          	$contract_number = $ContractModel->get(['id' => $contract_id])['contract_number'];
          	//学员表订单用逗号连接
          	$contract_number_str = $res_student['contract_number'];
            if($contract_number_str){
                $contract_number_str = $contract_number_str.','.$contract_number;
            }else{
                $contract_number_str = $contract_number;
            }
			
			//资金分配
            $data_checked_ids = [];
            $res_course_checked_ids = (new CourseContractModel())->where(['contract_id' => $contract_id])->select();
            foreach ($res_course_checked_ids as $value){
                $data_checked_ids[] = $value['id'].'-1';  //课程
            }
            $res_grades_checked_ids = (new GradesContractModel())->where(['contract_id' => $contract_id])->select();
            foreach ($res_grades_checked_ids as $value){
                $data_checked_ids[] = $value['id'].'-2';  //班级
            }
            $res_goods_checked_ids = (new GoodsContractModel())->where(['contract_id' => $contract_id])->select();
            foreach ($res_goods_checked_ids as $value){
                $data_checked_ids[] = $value['id'].'-3';  //物品
            }
			
			
            $contract = $ContractModel->get(['id' => $contract_id]);
            $amount_allocation =  $data['net_receipts'];
            if($amount_allocation > 0){
                $checked_ids = implode(',',$data_checked_ids);//资金分配
                $checked_ids_arr = explode(',',$checked_ids);

                //规则：默认先把物品的钱付完
                for($h = 0; $h < count($checked_ids_arr); $h ++){
                    $pos_value_arr = explode('-',$checked_ids_arr[$h]);
                    if($amount_allocation > 0) {
                        if ($pos_value_arr[1] == 3) {  //物品
                            $res_good = (new GoodsContractModel())->get(['id' => $pos_value_arr[0]]);
                            $des_good_amount = (($res_good['net_receipts'] - $res_good['assessed_amount']) - $res_good['payment']);
                            if($amount_allocation >= $des_good_amount){
                                $amount_allocation = $amount_allocation - $des_good_amount;
                                $des_good_amount_ = $res_good['payment'] + $des_good_amount;
                                $payment_balance = $res_good['payment_balance'] + $des_good_amount;
                                (new GoodsContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_, 'payment_balance' => $payment_balance]);
                            }else{
                                $amount_allocation = 0;
                                $des_good_amount_ = $res_good['payment'] + $amount_allocation;
                                $payment_balance = $res_good['payment_balance'] + $des_good_amount;
                                (new GoodsContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $des_good_amount_,'payment_balance' => $payment_balance]);
                            }
                        }
                    }
                }
                //分课程-分班级-求总应收金额
                if($amount_allocation > 0) {
                    $net_receipts_amount_total = 0;
                    for ($h = 0; $h < count($checked_ids_arr); $h++) {
                        $pos_value_arr = explode('-', $checked_ids_arr[$h]);
                        if ($pos_value_arr[1] == 1) {  //课程
                            $res_course = (new CourseContractModel())->get(['id' => $pos_value_arr[0]]);
                            $net_receipts_amount_total = $net_receipts_amount_total + ($res_course['net_receipts'] - $res_course['assessed_amount']);
                        } else if ($pos_value_arr[1] == 2) {   //班级
                            $res_grades = (new GradesContractModel())->get(['id' => $pos_value_arr[0]]);
                            $net_receipts_amount_total = $net_receipts_amount_total + ($res_grades['net_receipts'] - $res_grades['assessed_amount']);
                        }

                    }


                    //分配
                    for ($h = 0; $h < count($checked_ids_arr); $h++) {
                        $pos_value_arr = explode('-', $checked_ids_arr[$h]);
                        if ($pos_value_arr[1] == 1) {  //课程
                            $res_course = (new CourseContractModel())->get(['id' => $pos_value_arr[0]]);
                            $rate_amount = round(($res_course['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
                            $rate_amount_ = $res_course['payment'] + $rate_amount;
                            $payment_balance = $res_course['payment_balance'] + $rate_amount;
                            (new CourseContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]);  //更新付款金额


                            //更新合同应收分配课时
                            $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
                            $nums = round(($rate_amount / $price_),2);

                            $course_paid_nums_arr = explode(',',$contract['course_paid_nums']);
                            $course = explode(',',$contract['course']);
                            for($l = 0; $l < count($course); $l ++){
                                if($course[$l] == $res_course['course_id']){
                                    $course_paid_nums_arr[$l] = $course_paid_nums_arr[$l] + $nums;
                                }
                            }
                            $contract['course_paid_nums'] = implode(',',$course_paid_nums_arr);


                        } else if ($pos_value_arr[1] == 2) {   //班级
                            $res_grades = (new GradesContractModel())->get(['id' => $pos_value_arr[0]]);
                            $rate_amount = round(($res_grades['net_receipts'] / $net_receipts_amount_total) * $amount_allocation); //四舍五入取整
                            $rate_amount_ = $res_grades['payment'] + $rate_amount;
                            $payment_balance = $res_grades['payment_balance'] + $rate_amount;
                            (new GradesContractModel())->where(['id' => $pos_value_arr[0]])->update(['payment' => $rate_amount_, 'payment_balance' => $payment_balance]); //更新付款金额

                            //更新合同应收分配课时
                            $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
                            $nums = round(($rate_amount / $price_),2);

                            $grades_course_paid_nums_arr = explode(',',$contract['grades_course_paid_nums']);
                            $grades_course = explode(',',$contract['grades_course']);
                            for($l = 0; $l < count($grades_course); $l ++){
                                if($grades_course[$l] == $res_grades['course_id']){
                                    $grades_course_paid_nums_arr[$l] = $grades_course_paid_nums_arr[$l] + $nums;

                                }
                            }

                            $contract['grades_course_paid_nums'] = implode(',',$grades_course_paid_nums_arr);
                        }

                    }
                }

            }
			
			//学费余额
            $payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $contract_id])->sum('payment_balance');
            $payment_course_balance = (new CourseContractModel())->where(['contract_id' => $contract_id])->sum('payment_balance');
            $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和

            $contract_data = [];
            $contract_data['course_paid_nums'] = $contract['course_paid_nums'];
            $contract_data['grades_course_paid_nums'] = $contract['grades_course_paid_nums'];
            $contract_data['balance'] = $payment_money_balance;  //学费余额(不包含物品费用)

            $res_contract = $ContractModel->save($contract_data, ['id' => $contract_id]);
			
			//更新出库数量
            $result_goods =  (new GoodsContractModel())->where(['student_id'=>$data['student_id'], 'contract_id' => $contract_id])->select();
            foreach ($result_goods as $value){
                $res_goods_model = (new GoodsModel())->get(['id' => $value['goods_id'], 'campus_id' => $value['campus_id']]);
                $out_nums = $res_goods_model['out_nums'] + $value['goods_num'];  //出库
                if($res_goods_model['type'] == 0){  //物品
                    $residue_num = $res_goods_model['put_nums'] - $out_nums;  //剩余库存
                    (new GoodsModel())->where(['id' => $value['goods_id'], 'campus_id' => $value['campus_id']])->update(['out_nums' => $out_nums, 'residue_num' => $residue_num]);
                }else if($res_goods_model['type'] == 1){  //杂费
                    (new GoodsModel())->where(['id' => $value['goods_id'], 'campus_id' => $value['campus_id']])->update(['out_nums' => $out_nums]);
                }

            }
			   //根据学员ID更新学员表的报名状态及合同编号且将非正式学员转为正式学员
            (new StudentModel())->save(['sign_up'=>1,'is_audition'=>2,'contract_number'=>$contract_number_str,'sign_up_date'=>$data['signing_date']], ['id' => $data['student_id']]);

			 // 报读课程记录
            $contract = (new ContractModel())->get(['id' => $contract_id]);
            if($contract['course'] != null && strlen($contract['course']) > 0) {
                CommonService::writeCourseRecord($contract->contract_number, $contract->course, $contract->campus_id, 1);
            }
            // 报读班级课程记录
            if($contract['grades_course'] != null && strlen($contract['grades_course']) > 0) {
                CommonService::writeCourseRecord($contract->contract_number, $contract->grades_course, $contract->campus_id, 2);
            }
            // 生成已签约客户
            CommonService::writeSignContract($contract->student_id, $contract->contract_number, 1);
			
			 //将入班学员插入班级
            $grades_res = (new GradesContractModel())->where(['contract_id' => $contract_id])->select();
            foreach ($grades_res as $value){
                $grades_id = $value['grades_id']; //班级ID
                $student_id = $value['student_id'];//学员ID
                $room_seat = $value['room_seat']; //教室
                $class_num = 0; //课时数量
                $give_class_num = $value['give_class_num']; //赠送课时

                $grades_item = (new GradesDetailsModel())->get(['id' => $grades_id]);
                $student_item = (new StudentModel())->get(['id' => $student_id]);

                //分班
                $arr_room_id = explode(',',$grades_item['room_id']);
                $arr_subject_class = [];  //班级座位
                for ($i=0; $i < count($arr_room_id); $i ++){
                    $item_class = [];
                    $item_class['class_subject_id'] = $grades_id;
                    $item_class['campus_id'] = $grades_item['campus_id'];
                    $item_class['student_id'] = $student_id;
                    $item_class['student_name'] = $student_item['name'];
                    $item_class['room_id'] = $arr_room_id[$i];
                    $item_class['contract_number'] =$contract['contract_number'];; //合同编号
                    $item_class['status'] = 2; //班级分配
                    if($room_seat != null && strlen($room_seat) > 0) {
                        $seat_arr = explode(',', $room_seat);
                        for($j =0; $j < count($seat_arr); $j ++){
                            if(strpos($seat_arr[$j],$arr_room_id[$i]) !== false){
                                $item_class['seat_number'] = explode('-',$seat_arr[$j])[1];
                                break;
                            }
                        }

                    }
                    (new GradesDetailsModel())->where(['id' => $grades_id])->update(['status' => 1]);
                    $item_class['student_type'] = 1; //学员
                    $arr_subject_class[] = $item_class;
                }


                //排课
                $student_add_Infos_arr = [];
                $class_res = (new GradesDetailsListsModel())->where(['class_manage_id' => $grades_id])->select();
                foreach ($class_res as $value_){
                    /**********判断是否冲突*************/
                    $count_num = (new StudentSubjectInfosClassModel())->where(['contract_number' => $contract['contract_number'], 'class_manage_details_id' => $value_['id'],'student_id' => $student_id, 'report_status' => 2])->count();
                    if($count_num > 0){
                        continue;
                    }

                    $item_infos = [];
                    $item_infos['class_manage_details_id'] =  $value_['id']; //节课ID
                    $item_infos['class_subject_id'] = $value_['class_manage_id']; //分班ID
                    $item_infos['campus_id'] =  $value_['campus_id']; //校区ID
                    $item_infos['student_id'] = $student_id;//学生ID
                    $item_infos['student_name']  =  $student_item['name']; //学生姓名
                    $item_infos['room_name'] = $value_['class_room']; //教室名称
                    $item_infos['weekday'] =  $value_['weekday']; //星期
                    $item_infos['class_date'] = $value_['class_date']; //开课日期
                    $item_infos['course_id'] = $value_['course_id']; //课程ID
                    $item_infos['contract_number'] = $contract['contract_number'];
                    $item_infos['room_id'] = $value_['class_room_id'];//教室ID
                    $item_infos['report_status'] = 2; //班级
                    $item_infos['surplus_class_elimination'] = $class_num; //剩余课时
                    $item_infos['surplus_class_elimination_give'] = $give_class_num; //赠送剩余课时
                    $start = strtotime($value_['class_subject_start']);  //开始时间
                    $end = strtotime($value_['class_subject_end']);  //结束时间
                    $item_infos['duration'] = ceil(($end - $start)/60); //时长
                    $student_add_Infos_arr[] = $item_infos;
                }

                if(count($arr_subject_class) > 0){
                    (new StudentSubjectClassModel())->saveAll($arr_subject_class);
                }

                if(count($student_add_Infos_arr) > 0){
                    (new StudentSubjectInfosClassModel())->saveAll($student_add_Infos_arr);
                }
            }
		$contract['campus_name'] = (new CampusModel())->get(['id' => $contract['campus_id']])['campus_name'];
		$res = (new StudentModel())->get(['id' => $contract['student_id']]);
		if($res){
			if($res['user_edu_id'] == null || $res['user_edu_id'] == 0){  //未指定教务
				$contract['user_edu_status'] = 0;  //未指定
			}else{
				$contract['user_edu_status'] = 1;  //已指定
			}
        }
		$this->data['order'] = $contract; //订单详情
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 获取试听课节列表
	 * User: wufeng
	 * Date: 2020/04/01
	 *
	 * @param $params
	 * @return array
	 */
    public function achieveAuditionClassDayLists($params)
    {
        try {
        	$where = [];
			//按班级、老师、教室搜索
			if (isset($params['word']) && '' !== $params['word']) {
				$where['class_grades_name|headmaster|teacher|assistant|class_room'] = ['like', '%'.$params['word'].'%'];
			}
			if (isset($params['start_date']) && '' !== $params['start_date'] && isset($params['end_date']) && '' !== $params['end_date']) {
				if($params['start_date'] == $params['end_date']){
					$where['class_date'] = $params['start_date'];
				}else{
					$start = date('Y-m-d', strtotime($params['start_date']));
					$end = date('Y-m-d', strtotime($params['end_date']));
					$where['class_date'] = [['egt', $start], ['lt', $end]];
				}

			}else if (isset($params['start_date']) && '' !== $params['start_date'] && '' == $params['end_date'] && null == $params['end_date']) {
				$where['class_date'] = $params['start_date'];
			}else if (isset($params['end_date']) && '' !== $params['end_date'] && '' == $params['start_date'] && null == $params['start_date']) {
				$where['class_date'] = $params['end_date'];
			}else{
				$where['class_date'] = ['egt',date('Y-m-d')];
			}
			$where['campus_id'] = $params['campus_id'];
			$where['status'] = 0; //未上课
			$this->data = (new GradesDetailsListsModel())
				->where($where)
				->order('id desc')
				->select()
				->toArray();
			foreach ($this->data as &$item) {
				$item['course_type'] = (new CourseModel())->get(['id' => $item['course_id']])['course_type'];
				$grades_id = $item['class_manage_id']; //班级ID
				$arrs = (new StudentSubjectClassModel())->where('class_subject_id', $grades_id)->column('student_id');
                //已报
                $item['already_reported_num'] = \count(array_unique($arrs));
				$item['preoccupation'] = (new GradesDetailsModel())->get(['id' => $grades_id])['preoccupation'];
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
     * 生成单号.
     * @return string
     */
    public function generateNumber()
    {
        $number = '';
        $year = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        $number .= $year[intval(date('Y')) - 2019] . date('mdHis').substr(microtime(), 2, 3) . sprintf('%02d', rand(0, 99));
        return $number;
    }

    /**
     * 产品/班级
     * User: wufeng
     * Date: 2020/01/10.
     *
     * @param $params
     *
     * @return array
     */
    public function productClass($params)
    {
        try {
            $where = $where_goods = $where_course = [];
			if(xcxapi_get_current_wtype() == 4 || xcxapi_get_current_wtype() == 5){
				$where['campus_id'] = xcxapi_get_current_campus_id();
				$where_goods['campus_id'] = xcxapi_get_current_campus_id();
				$where_course['campus_id'] = xcxapi_get_current_campus_id();
				$where_class['campus_id'] = xcxapi_get_current_campus_id();
			}elseif (xcxapi_get_current_wtype() == 2 || xcxapi_get_current_wtype() == 3){
				$where['campus_id'] = ['in',xcxapi_get_current_campus_id()];
				$where_goods['campus_id'] = ['in',xcxapi_get_current_campus_id()];
				$where_course['campus_id'] = ['in',xcxapi_get_current_campus_id()];
				$where_class['campus_id'] = ['in',xcxapi_get_current_campus_id()];
			}
			if(1 === (int) $params['table_type']){
				//0，1 为物品和杂费
				if(0 === (int) $params['api_type'] || 1 === (int) $params['api_type']){
					$where_goods['type'] = $params['api_type'];
					if (isset($params['word']) && '' !== $params['word']) {
						$where_goods['goods_name'] = ['like', '%'.$params['word'].'%'];
					}
					$where_goods['residue_num'] = ['gt',0];
					$this->data['good'] = (new GoodsModel())
						->where($where_goods)
						->order('id desc')
						->field('id,goods_name,type,unit,price')
						->select()
						->toArray()
					;
					foreach ($this->data['good'] as &$item) {
						$item['price'] = $item['price'] / 100;
						$item['type_pro'] = 1;
						if (1 === (int) $item['type']) {
							$item['type_text'] = '杂费';
						} else {
							$item['type_text'] = '物品';
						}
					}
				}elseif(41 === (int) $params['api_type'] || 42 === (int) $params['api_type'] || 43 === (int) $params['api_type']){
					$where_course['course_type'] = $params['api_type'];
					$where_course['status'] = 1;
					//按手机号、姓名、顾问搜索
					if (isset($params['word']) && '' !== $params['word']) {
						$where_course['course_name'] = ['like', '%'.$params['word'].'%'];
					}
					$course = (new CourseModel())
						->where($where_course)
						->order('id desc')
						->field('id,course_name as goods_name,course_type as type,class_num,unit,price')
						->select()
						->toArray();
					foreach ($course as &$item) {
						$item['type_pro'] = 2;
						$item['price'] = $item['price'] / 100;
						$item['type_text'] = DictionaryModel::getById($item['type'], 'name');
					}
					$this->data['good'] = $course;
				}else{
					if (isset($params['word']) && '' !== $params['word']) {
						$where_goods['goods_name'] = ['like', '%'.$params['word'].'%'];
					}
					$where_goods['residue_num'] = ['gt',0];
					$this->data['good'] = (new GoodsModel())
						->where($where_goods)
						->order('id desc')
						->field('id,goods_name,type,unit,price')
						->select()
						->toArray()
					;
					foreach ($this->data['good'] as &$item) {
						$item['price'] = $item['price'] / 100;
						$item['type_pro'] = 1;
						if (1 === (int) $item['type']) {
							$item['type_text'] = '杂费';
						} else {
							$item['type_text'] = '物品';
						}
					}
					$where_course['status'] = 1;
					//按手机号、姓名、顾问搜索
					if (isset($params['word']) && '' !== $params['word']) {
						$where_course['course_name'] = ['like', '%'.$params['word'].'%'];
					}
					$course = (new CourseModel())
						->where($where_course)
						->order('id desc')
						->field('id,course_name as goods_name,course_type as type,class_num,unit,price')
						->select()
						->toArray();
					foreach ($course as &$item) {
						$item['type_pro'] = 2;
						$item['price'] = $item['price'] / 100;
						$item['type_text'] = DictionaryModel::getById($item['type'], 'name');
					}
					$this->data['good'] = array_merge($this->data['good'], $course);
				}
			}elseif(2 === (int) $params['table_type']){
				if (isset($params['word']) && '' !== $params['word']) {
					$where_class['grades_name|teacher|room_text'] = ['like', '%'.$params['word'].'%'];
				}
				if (isset($params['start_date']) && '' !== $params['start_date'] && isset($params['end_date']) && '' !== $params['end_date']) {
					$start = date('Y-m-d H:i:s', strtotime($params['start_date']));
					$end = date('Y-m-d H:i:s', strtotime($params['end_date']) + 86400);
					$where_class['create_time'] = [['egt', $start], ['lt', $end]];

				}else if (isset($params['start_date']) && '' !== $params['start_date'] && '' == $params['end_date'] && null == $params['end_date']) {
					$start = date('Y-m-d H:i:s', strtotime($params['start_date']));
					$end = date('Y-m-d H:i:s', strtotime($params['start_date']) + 86400);
					$where_class['create_time'] = [['egt', $start], ['lt', $end]];
				}else if (isset($params['end_date']) && '' !== $params['end_date'] && '' == $params['start_date'] && null == $params['start_date']) {
					$start = date('Y-m-d H:i:s', strtotime($params['end_date']));
					$end = date('Y-m-d H:i:s', strtotime($params['end_date']) + 86400);
					$where_class['create_time'] = [['egt', $start], ['lt', $end]];
				}
				$where_class['graduation_status'] = 0; //未结业
				$this->data['class'] = (new GradesDetailsModel())
					->where($where_class)
					->order('id desc')
					->field('id,course_id,room_text,preoccupation,grades_name,teacher,already_class,already_arranged')
					->select()
					->toArray()
				;
				foreach ($this->data['class'] as &$item) {
					$res_course = (new CourseModel())->get($item['course_id']);
					$item['type_pro'] = 3;
					$item['class_num'] = $res_course['class_num'];
					$item['course_name'] = $res_course['course_name'];
					$item['room_text_unique'] = implode(',',array_unique(explode(",",$item['room_text'])));
					$item['price'] = $res_course['price'] / 100;
					$item['unit'] = $res_course['unit'];
					if (0 === (int) $item['preoccupation']) {
						$item['preoccupation_text'] = '无限';
					} else {
						$item['preoccupation_text'] = $item['preoccupation'];
					}
					$item['already_recruited'] = (new CourseLogModel())->where(['course' => ['like', $item['course_id'].'%']])->count();
					// 首次上课日期
					$res = (new GradesDetailsListsModel())->get(['class_manage_id' => $item['id']]);
					$item['first_class_date'] = $res['class_date'].'-'.$res['weekday'].'-'.$res['class_subject_start'].'-'.$res['class_subject_end'];
				}
			}
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 班型、物品类型
	 * User: wufeng
	 * Date: 2020/04/23
	 *
	 * @return array
	 */
	public function classTypeGoodType()
	{
		try {
			$this->data = (new DictionaryModel())
				->where('type', 9)
				->field('id,name')
				->select()
				->toArray()
			;
			$good_0[] = ['id'=>0,'name'=>'物品'];
			$good_1[] = ['id'=>1,'name'=>'杂费'];
			$this->data = array_merge($this->data,$good_0,$good_1);
			if (empty($this->data)) {
				throw new BaseException('NO_DATA');
			}
		} catch (\Exception $e) {
			$this->errorMessage($e, '');
		}

		return $this->return;
	}

    /**
     * 收款归属、支付方式
     * User: wufeng
     * Date: 2020/01/11.
     *
     * @return array
     */
    public function receivablesPaymentMethod()
    {
        try {
            $this->data['receivables'] = (new DictionaryModel())
                ->where('type', 24)
                ->field('id,name')
                ->select()
                ->toArray()
            ;
            $this->data['payment_method'] = (new DictionaryModel())
                ->where('type', 20)
                ->field('id,name')
                ->select()
                ->toArray()
            ;
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, '');
        }

        return $this->return;
    }

    /**
     * 实例化
     * User: wufeng
     * Date: 2019/5/28.
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->customerValidate = new CustomerValidate();
    }
}
